package com.atguigu.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT=6667;
    public GroupChatServer(){
        try {
            //得到选择器
            selector=Selector.open();
            //得到监听通道
            listenChannel=ServerSocketChannel.open();
            //绑定端口
            listenChannel.bind(new InetSocketAddress(PORT));
            //设置非阻塞
            listenChannel.configureBlocking(false);
            //将通道注册到选择器
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //监听
    public void listen(){
        try{
            //循环处理
            while(true){
                int count = selector.select(2000);
                if(count>0){
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        if(key.isAcceptable()){
                            //连接事件
                            SocketChannel socketChannel = listenChannel.accept();
                            //设置非阻塞
                            socketChannel.configureBlocking(false);
                            //注册到选择器
                            socketChannel.register(selector,SelectionKey.OP_READ);
                            //提示
                            System.out.println(socketChannel.getRemoteAddress()+"上线");
                        }
                        if(key.isReadable()){
                            //read事件
                            readData(key);
                        }
                        //删除当前key，防止重复处理
                        iterator.remove();
                    }
                }else{
                    System.out.println("等待");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //读取客户端消息
    private void readData(SelectionKey selectionKey){
        SocketChannel channel = null;
        try {
            //得到channel
            channel = (SocketChannel) selectionKey.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if(count>0){
                //将缓冲区数据输出
                String msg = new String(buffer.array());
                System.out.println("from 客户端"+msg);
                //向其他客户端转发消息
                sendInfoToOtherClients(msg,channel);
            }
        }catch (IOException e){
            try {
                System.out.println(channel.getRemoteAddress()+"离线");
                //取消注册
                selectionKey.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    //转发消息给其他的客户
    private void sendInfoToOtherClients(String msg,SocketChannel self) throws IOException {
        System.out.println("服务器转发消息...");
        //遍历所有注册到selector的scoketchannel
        Set<SelectionKey> keys = selector.keys();
        for(SelectionKey key:keys){
            //根据key获取channel
            Channel targetChannel = key.channel();
            //排除自己
            if(targetChannel instanceof SocketChannel&&targetChannel!=self){
                SocketChannel dest = (SocketChannel) targetChannel;
                //将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //buffer数据写入通道
                dest.write(buffer);
            }
        }

    }
    public static void main(String[] args) {
        //创建一个服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
